<?php

namespace App\Services;


use App\Models\TokenSocket;
use App\Models\User;
use GatewayWorker\Lib\Gateway;

use Illuminate\Support\Facades\Log;

use App\Events\UserEvent;
use App\Models\TemporaryToken;

class WebSocketServices
    {

    // public static $app = null;
    public static function onWorkerStart($businessWorker)
        {
        // Log::debug("socket", [$businessWorker]);
        }

    public static function onConnect($client_id)
        {

        }

    public static function onWebSocketConnect($client_id, $data)
        {
        $tt = TemporaryToken::where("api_token", $data['get']['token'])->first();

        if ($tt) {
            $tt->online = 1;
            $tt->save();
            TokenSocket::create(['token_id' => $tt->id, 'socket_fd' => $client_id]);
            wsSend("", "连接成功！" . $client_id, $client_id);
            }
        else {
            wsFail("用户未授权访问！", $client_id);
            self::onClose($client_id);
            }
        }

    public static function onMessage($client_id, $message)
        {
        // $userapp = self::$app;
        $tt = TokenSocket::where("socket_fd", $client_id)->first();
        if ($tt->token && !$tt->token->is_time_out) {
            $tt->token->touch();
            // $userapp->run();
            // $userapp->make("events")->dispatch(new UserEvent($tt));
            }
        else {
            wsFail("用户超时已过期！", $client_id);
            self::onClose($client_id);
            }
        }

    public static function onClose($client_id)
        {
        $tt    = TokenSocket::where("socket_fd", $client_id)->first();
        $token = $tt->token;
        if ($token->sockets->count() == 1) {
            $token->online = 0;
            $token->save();
            }
        $tt->delete();
        }
    }
